//
//  Movie.swift
//  MovieAppDemo
//
//  Created by Demo on 2025/1/25.
//
import Foundation
 
struct Response: Decodable {
    var code: Int
    var msg: String?
    var data: [MainPica]
    var total: Int
    var page: Int
    var page_size: Int
}

struct MainPica: Identifiable, Decodable, Equatable {
    var id: Int
    var name: String
    var cover: String
    var longs: Int
    var tags: [String]
    var desc: String
    var chinese_title: String
    var add_time: String
    var type: Int
    var like_count: Int
    var read_count: Int
    var true_page_count: Int
    var url: String
    var author: String
    var fav_time: String
    var video_type: Int
    
    
    enum CodingKeys: String, CodingKey {
        case id, name, cover, longs, tags, desc, chinese_title, add_time, type, read_count, true_page_count, url, author, like_count,fav_time,video_type
    }
    
    static func ==(lhs: MainPica, rhs: MainPica) -> Bool {
            return lhs.id == rhs.id && lhs.name == rhs.name
        }
}


 

var mainpicas: [MainPica] = [
    MainPica(
        id: 34826,
        name: "标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题1",
        cover: "http://www.cosck.com:444/video/2023-06-01/5617.jpg",
        longs: 100,
        tags: ["标签标签1", "标签2", "标签3","标签标签1", "标签2", "标签3"],
        desc: "介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容",
        chinese_title: "中文标题",
        add_time: "2025-01-10",
        type: 3,
        like_count: 200,
        read_count: 300,
        true_page_count: 20,
        url: "http://www.cosck.com:444/video/2023-06-01/5617.mp4",
        author: "作者",
        fav_time:"2025-02-01 12:10:00",
        video_type:0
    ),
    MainPica(
        id: 2,
        name: "标题2",
        cover: "http://www.cosck.com:444/video/2022-06-01/3579.jpg",
        longs: 100,
        tags: ["标签1", "标签2", "标签3"],
        desc: "介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容",
        chinese_title: "中文标题",
        add_time: "2025-01-10",
        type: 1,
        like_count: 200,
        read_count: 300,
        true_page_count: 20,
        url: "http://www.cosck.com:444/video/2022-06-01/3579.mp4",
        author: "作者",
        fav_time:"2025-02-01 12:10:00",
        video_type:1
    ),
    MainPica(
        id: 3,
        name: "标题3",
        cover: "http://www.cosck.com:444/video/2022-06-01/3581.jpg",
        longs: 100,
        tags: ["标签1", "标签2", "标签3"],
        desc: "介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容",
        chinese_title: "中文标题",
        add_time: "2025-01-10",
        type: 1,
        like_count: 200,
        read_count: 300,
        true_page_count: 20,
        url: "http://www.cosck.com:444/video/2022-06-01/3581.mp4",
        author: "作者",
        fav_time:"2025-02-01 12:10:00",
        video_type:0
    )
    ,
    MainPica(
        id: 4,
        name: "标题4",
        cover: "http://www.cosck.com:444/video/2022-06-01/3582.jpg",
        longs: 100,
        tags: ["标签1", "标签2", "标签3"],
        desc: "介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容",
        chinese_title: "中文标题",
        add_time: "2025-01-10",
        type: 1,
        like_count: 200,
        read_count: 300,
        true_page_count: 20,
        url: "http://www.cosck.com:444/video/2022-06-01/3582.mp4",
        author: "作者",
        fav_time:"2025-02-01 12:10:00",
        video_type:0
    )
    ,
    MainPica(
        id: 5,
        name: "标题5",
        cover: "http://www.cosck.com:444/video/2022-04-01/2708.jpg",
        longs: 100,
        tags: ["标签1", "标签2", "标签3"],
        desc: "介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容介绍内容",
        chinese_title: "中文标题",
        add_time: "2025-01-10",
        type: 1,
        like_count: 200,
        read_count: 300,
        true_page_count: 20,
        url: "http://www.cosck.com:444/video/2022-04-01/2708.mp4",
        author: "作者",
        fav_time:"2025-02-01 12:10:00",
        video_type:0
    )
]

class MainPicaViewModel: ObservableObject {
    @Published var isLoading = true
    @Published var errorMessage: String?
    
    @Published var homeBanners: [MainPica] = []
    @Published var homehots: [MainPica] = []
    @Published var homecomics: [MainPica] = []
    @Published var homevideos: [MainPica] = []
    @Published var homeanimates: [MainPica] = []
    @Published var nowfavs: [MainPica] = []
    @Published var lists: [MainPica] = []
    @Published var tuijian: [MainPica] = []
    @Published var video_list: [MainPica] = []
    @Published var search_tuijian: [MainPica] = []
    @Published var search_dats: [MainPica] = []
    @Published var homehis: [MainPica] = []
    
    // 修改 fetchMainPicas 方法，增加一个 completion handler 来返回数据
    func fetchMainPicas(page: Int, pageSize: Int, type: Int=0, tag: String="",order_by: Int = 1, fav_type: Int = 0,is_banner: Int = 0,video_id: Int = 0,name: String = "", completion: @escaping ([MainPica]?) -> Void) {
        guard let url = URL(string: "http://www.cosck.com:39999/api/pica/pica_main/list?page=\(page)&page_size=\(pageSize)&type=\(type)&order_by=\(order_by)&tag=\(tag)&fav_type=\(fav_type)&is_banner=\(is_banner)&video_id=\(video_id)&name=\(name)") else {
            self.errorMessage = "Invalid URL"
            completion(nil)
            return
        }
        
        
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"  // 设置请求方法
        request.setValue("dev", forHTTPHeaderField: "token")  // 设置 header: token=dev
        
        isLoading = true
        URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                self.isLoading = false
                
                if let error = error {
                    self.errorMessage = "Error: \(error.localizedDescription)"
                    completion(nil)
                    return
                }
                
                guard let data = data else {
                    self.errorMessage = "No data received"
                    completion(nil)
                    return
                }
                
                do {
                    // 解码为 Response 类型
                    let decodedResponse = try JSONDecoder().decode(Response.self, from: data)
                    completion(decodedResponse.data)  // 将 data 数组传递给 completion handler
                } catch {
                    self.errorMessage = "Failed to decode JSON: \(error.localizedDescription)"
                    print("Failed to decode JSON: \(error)")
                    completion(nil)
                }
            }
        }.resume()
    }
    
    func get_home() {
        // 调用 fetchMainPicas 并通过回调获取数据
        fetchMainPicas(page: 1, pageSize: 10, fav_type:1) { data in
            if let data = data {
                self.homehots = data
            }
        }
        
        
        
        fetchMainPicas(page: 1, pageSize: 10, type: 0,is_banner:1) { data in
            if let data = data {
                self.homeBanners = data
            }
        }
        
        fetchMainPicas(page: 1, pageSize: 10, type: 1) { data in
            if let data = data {
                self.homevideos = data
            }
        }
        
        fetchMainPicas(page: 1, pageSize: 10, type: 2) { data in
            if let data = data {
                self.homeanimates = data
            }
        }
        
        fetchMainPicas(page: 1, pageSize: 10, type: 3) { data in
            if let data = data {
                self.homecomics = data
            }
        }
    }
    

    func get_list(type: Int, page: Int = 1,tag:String = "",fav_type:Int = 0,order_by:Int=1) {
        
        // 调用 fetchMainPicas 并通过回调获取数据
        fetchMainPicas(page: page, pageSize: 20, type: type,tag:tag,order_by:order_by, fav_type: fav_type) { data in
            if let data = data {
                if page == 1 {
                    // 如果是第一页，直接替换列表
                    self.lists = data
                } else {
                    // 如果不是第一页，将新数据追加到现有数组
                    self.lists.append(contentsOf: data)
                }
                self.isLoading = false
            }
        }
    }
    
    func get_tuijian(type: Int, page: Int = 1,order_by:Int = 3) {
        // 调用 fetchMainPicas 并通过回调获取数据
        fetchMainPicas(page: page, pageSize: 10, type: type, order_by: order_by) { data in
            if let data = data {
                if page == 1 {
                    // 如果是第一页，直接替换列表
                    self.tuijian = data
                } else {
                    // 如果不是第一页，将新数据追加到现有数组
                    self.tuijian.append(contentsOf: data)
                }
                self.isLoading = false
            }
        }
    }
    
    
    func get_list_back(type: Int, page: Int = 1, fav_type: Int = 0, completion: (() -> Void)? = nil) {
        // 调用 fetchMainPicas 并通过回调获取数据
        fetchMainPicas(page: page, pageSize: 20, type: type, fav_type: fav_type) { data in
            if let data = data {
                if page == 1 {
                    // 如果是第一页，直接替换列表
                    self.lists = data
                } else {
                    self.lists.append(contentsOf: data)
                }
                self.isLoading = false
            }
            // 调用回调，通知加载完成
            completion?()
        }
    }
    
    
    func get_videos(type: Int, page: Int = 1,video_id: Int = 0) {
        // 调用 fetchMainPicas 并通过回调获取数据
        fetchMainPicas(page: page, pageSize: 10, type: type, video_id: video_id) { data in
            if let data = data {
                if page == 1 {
                    // 如果是第一页，直接替换列表
                    self.video_list = data
                } else {
                    // 如果不是第一页，将新数据追加到现有数组
                    self.video_list.append(contentsOf: data)
                }
                self.isLoading = false
            }
        }
    }

    func get_tj_data() {
        // 调用 fetchMainPicas 并通过回调获取数据
        fetchMainPicas(page: 1, pageSize: 10,order_by:3) { data in
            if let data = data {
                self.search_tuijian = data
            }
        }
    }
    
    func get_search_data(name:String) {
        // 调用 fetchMainPicas 并通过回调获取数据
        fetchMainPicas(page: 1, pageSize: 10,name:name) { data in
            if let data = data {
                self.search_dats = data
            }
        }
    }
    
    
    //获取最后阅读的一个main
    func get_last_main(page: Int = 1, fav_type: Int = 2, completion: (() -> Void)? = nil) {
        fetchMainPicas(page: page, pageSize: 1, fav_type:fav_type) { data in
            if let data = data {
                self.homehis = data
            }
            // 调用回调，通知加载完成
            completion?()
        }
    }


}

